package com.common.library.net;

import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.download.DownloadListener;
import com.yolanda.nohttp.download.DownloadQueue;
import com.yolanda.nohttp.download.DownloadRequest;
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.RequestQueue;

import org.json.JSONObject;

/**
 * @title 网络管理类
 * 网络请求的添加与取消。
 */
public class HttpQueue {

    public static HttpQueue mHttpQueue;
    private DownloadQueue mDownloadRequestQueue;

    public static HttpQueue newHttpQueue() {
        if (mHttpQueue == null) {
            mHttpQueue = new HttpQueue();
        }
        return mHttpQueue;
    }
    RequestQueue requestQueue;
    /**
     * 文件下载
     * */
    public void add(DownloadRequest request, DownloadListener responseListener) {
        getDownloadRequestRequestQueue().add(0, request, responseListener);
    }
    /**
     * 表单提交
     * */
    public void addJSONObject(Request<JSONObject> request, OnResponseListener responseListener) {
        getRequestQueue().add(0, request, responseListener);
    }
    /**
     * 字符串提交
     * */
    public void addString(Request<String> request, OnResponseListener responseListener) {
        getRequestQueue().add(0, request, responseListener);
    }
    public void cancelRequest(Object sign) {
        getRequestQueue().cancelBySign(sign);
    }
    public void cancelRequestAll() {
        getRequestQueue().cancelAll();
    }
    public void cancelDownloadQueue(Object sign) {
        getDownloadRequestRequestQueue().cancelBySign(sign);
    }
    public void cancelDownloadAll() {
        getDownloadRequestRequestQueue().cancelAll();
    }

    public void cancelAll() {
        getRequestQueue().cancelAll();
        getDownloadRequestRequestQueue().cancelAll();
    }
    /**
     * 下载请求队列
     * */
    public DownloadQueue getDownloadRequestRequestQueue() {
        if (mDownloadRequestQueue == null) {
            mDownloadRequestQueue = NoHttp.newDownloadQueue(3);//并发3条请求
        }
        return mDownloadRequestQueue;
    }
    /**
     * 普通请求队列
     * */
    public RequestQueue getRequestQueue() {
        if (requestQueue == null) {
            requestQueue = NoHttp.newRequestQueue(3);//并发3条请求
        }
        return requestQueue;
    }
}
